package com.example.demo.service.impl;

import com.example.demo.service.RedisService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, String value) {
        this.stringRedisTemplate.opsForValue().set(key, value);
    }

    public Long getTime(String key) {
        return this.stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    public void setExpire(String key, String value, long s) {
        this.stringRedisTemplate.opsForValue().set(key, value, s, TimeUnit.SECONDS);
    }

    public String get(String key) {
        return this.stringRedisTemplate.opsForValue().get(key);
    }

    public void delete(String key) {
        this.stringRedisTemplate.delete(key);
    }

    public Boolean expire(String key, int s) {
        return this.stringRedisTemplate.expire(key, s, TimeUnit.SECONDS);
    }


    public boolean verifyNumber(String key, int number) {
        String s = this.stringRedisTemplate.opsForValue().get(key);
        if (s == null) {
            this.stringRedisTemplate.opsForValue().set(key, String.valueOf(number), 5 * 60, TimeUnit.SECONDS);
        } else if (Integer.parseInt(s) <= 1) {
            return false;
        } else {
            String i = String.valueOf(Integer.parseInt(s) - 1);
            this.stringRedisTemplate.opsForValue().set(key,i, 5 * 60, TimeUnit.SECONDS);
        }
        return true;
    }
}
